package com.huodongrili.calender.data;

import java.util.HashMap;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.huodongrili.calender.data.DBTables.Sort;

public class SortData {

	private Context mContext;
	private static SortData mSort;
	public Map<String, Boolean> mDataMap;

	public static SortData getInstance(Context context) {
		if (mSort == null) {
			mSort = new SortData(context);

		}

		return mSort;
	}

	public SortData(Context context) {
		mContext = context.getApplicationContext();
	}

	public void realseSort() {
		mContext = null;
		mDataMap = null;
		mSort = null;
	}

	public void modifySort(String name, boolean isCheck) {
		SQLiteDatabase db = mContext.openOrCreateDatabase(
				Constant.LOCAL_DB_NAME, Context.MODE_WORLD_WRITEABLE, null);

		int v = isCheck == true ? 1 : 0;

		ContentValues cv = new ContentValues();
		cv.put(Sort.ENABLE, v);

		String[] args = { name };
		db.update(Sort.TABLE_NAME, cv, Sort.NAME + "=?", args);
		
		db.close();

	}

	public void getSort() {

		SQLiteDatabase db = mContext.openOrCreateDatabase(
				Constant.LOCAL_DB_NAME, Context.MODE_WORLD_READABLE, null);

		Cursor cursor = null;
		Map<String, Boolean> sortMap = null;

		try {

			cursor = db.rawQuery("select * from " + Sort.TABLE_NAME, null);
			if (cursor != null && cursor.getCount() > 0) {
				sortMap = new HashMap<String, Boolean>();
				cursor.moveToFirst();
				while (!cursor.isAfterLast()) {
					String name = cursor.getString(cursor
							.getColumnIndex(Sort.NAME));
					int index = cursor.getInt(cursor
							.getColumnIndex(Sort.ENABLE));

					boolean enable = index == 1 ? true : false;
					sortMap.put(name, enable);
					cursor.moveToNext();
				}

				mDataMap = sortMap;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (cursor != null) {
				cursor.close();
			}
			
			db.close();
		}

	}

}
